const http = require("http");

let data = "";
let header = "";

function request(options, postData, callback) {
  return new Promise((resolve, reject) => {
    // console.log(header)
    // options.headers = header || options.headers;
    const req = http.request(options, (res) => {
      console.log(`状态码: ${res.statusCode}`);
      console.log(`响应头: ${JSON.stringify(res.headers)}`);
      console.log(`请求路径：${res.req.path}`);
      res.setEncoding("utf8");
      res.on("data", (chunk) => {
        console.log(`响应主体: ${chunk}\n`);
        data += chunk;
      });
      res.on("end", () => {
        if (res.statusCode !== 200) {
          reject("服务器连接失败");
        } else {
          console.log("数据已全部获取");
          resolve(data)
        }
      });
    });

    req.on("error", (e) => {
      const msg = `请求遇到问题: ${e.message}`;
      // console.error(msg);
      reject(msg)
    });

    req.on("timeout", (e) => {
      const msg = `连接超时`;
      // console.error(msg);
      reject(msg)
    });

    // 将数据写入请求主体。
    req.write(postData);
    req.end();
  })
}

module.exports = request;
